/*******************************************************************************
 * Copyright (c) 2010, 2017 西安秦晔信息科技有限公司
 * Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 *******************************************************************************/
package com.qinyeit.serviceapp.service.branchs;

import com.qinyeit.serviceapp.entity.BranchPurchaseOrder;
import com.qinyeit.serviceapp.entity.BranchPurchaseOrderDetail;
import com.qinyeit.serviceapp.entity.PurchaseSpec;
import com.qinyeit.serviceapp.entity.enums.BranchPurchaseState;
import com.qinyeit.serviceapp.entity.enums.BranchPurchaseType;
import com.qinyeit.serviceapp.exception.BusinessRunTimeException;
import com.qinyeit.serviceapp.service.materials.PurchaseSpecService;
import com.qinyeit.serviceapp.service.organization.BranchService;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.repository.jdbc.PageNamedParameterJdbcTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.http.auth.BasicUserPrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 单店版 直配单、自采单
 */
@Slf4j
@Service
public class BranchOrderServiceImpl {

    @Resource(name = "branchJdbcTemplate")
    private PageNamedParameterJdbcTemplate branchJdbcTemplate;
    @Autowired
    private BranchService branchService;

    /**
     * 保存门店采购订单 总部订单为审核状态
     * @param order
     * @param detailList
     */
    public void saveBranchPurchaseOrders(BranchPurchaseOrder order, List<BranchPurchaseOrderDetail> detailList) {

        log.info("------------------------------baocun mendian order");

        //保存订单 总部订单为审核 -- 单店订单为 总部待发货 --
        //总部订单确认发货 -- 单店为 已审核
        //将门店id 转换为merchantid
        Long merchantId = branchService.getMerchantIdByBranchId(order.getBranchId());
        if (merchantId==null){
            throw new BusinessRunTimeException("商户不存在",10002);
        }
        if (order.getState()== BranchPurchaseState.AUDIT){
            saveOrderForWait(merchantId,order,detailList);
        }else if (order.getState()==BranchPurchaseState.DELIVERED){
            //修改单店订单为待收货确认
            saveOrderForAudit(merchantId,order,detailList);
        }

    }

    /**
     * 保存单店采购直配单 状态为 已审核 （待收货确认）
     * @param merchantId
     * @param order
     * @param detailList
     */
    private void saveOrderForAudit(Long merchantId, BranchPurchaseOrder order, List<BranchPurchaseOrderDetail> detailList) {
        //根据订单no 查询单店的采购单
        String sql = "SELECT * from purchase_orders where is_deleted = 0 and no = :no and merchant_id = :merchant_id";
        log.info("no:{}",order.getNo());
        log.info("merchant_id:{}",merchantId);
        QyMap params = QyMap.map("no",order.getNo()).setv("merchant_id",merchantId);
        Map<String,Object> orderData = branchJdbcTemplate.queryForMap(sql,params);

        sql = "UPDATE purchase_orders SET address=:address,amount=:amount,send_time=:send_time,remark=:remark,state=:state\n" +
                "WHERE id = :id";
        params = QyMap.map("id",orderData.get("id"))
                .setv("address",order.getAddress())
                .setv("amount",order.getAmount())
                .setv("send_time",order.getSendTime())
                .setv("remark",order.getRemark())
                .setv("state",PurchaseState.AUDIT.getKey());
        branchJdbcTemplate.update(sql,params);

        //删除订单明细
        sql = "DELETE from purchase_order_details where order_id = :order_id";
        params = QyMap.map("order_id",orderData.get("id"));
        branchJdbcTemplate.update(sql,params);

        //添加订单明细
        BranchPurchaseOrderDetail detail = null;
        if (CollectionUtils.isNotEmpty(detailList)){
            Map<String,?>[] maps = new Map[detailList.size()];
            for (int i = 0; i < detailList.size(); i++) {
                detail = detailList.get(i);
                params = QyMap.map("merchant_id",merchantId)
                        .setv("amount",detail.getSendCount()*detail.getSendPrice())
                        .setv("count",detail.getPurchaseCount())
                        .setv("name",detail.getName())
                        .setv("no",detail.getNo())
                        .setv("price",detail.getPurchasePrice())
                        .setv("purchase_spec_name",detail.getPurchaseSpec())
                        .setv("purchase_unit_name",detail.getPurchaseUnit())
                        .setv("chain_remark",detail.getGroupRemark())
                        .setv("spec",detail.getMaterialSpec())
                        .setv("order_id",orderData.get("id"))
                        .setv("real_price",detail.getSendPrice())
                        .setv("real_count",detail.getSendCount())
                        .setv("spec_id",detail.getSpecId())
                        .setv("storage_unit_name",detail.getStockUnit())
                        .setv("remark",detail.getBranchRemark());
                maps[i] = params;
            }
            sql = "INSERT INTO purchase_order_details (create_at,is_deleted,status,merchant_id,amount,count,name,no,price,purchase_spec_name," +
                    "purchase_unit_name,chain_remark,spec,order_id,real_price,real_count,spec_id,storage_unit_name,remark)\n" +
                    "VALUES(now(),0,0,:merchant_id,:amount,:count,:name,:no,:price,:purchase_spec_name," +
                    ":purchase_unit_name,:chain_remark,:spec,:order_id,:real_price,:real_count,:spec_id,:storage_unit_name,:remark)";
            branchJdbcTemplate.batchUpdate(sql,maps);
        }
    }

    /**
     * 保存单店采购直配单 状态位总部待发货
     * @param merchantId
     * @param order
     * @param detailList
     */
    private void saveOrderForWait(Long merchantId,BranchPurchaseOrder order, List<BranchPurchaseOrderDetail> detailList) {
        String sql = "INSERT INTO purchase_orders (create_at,is_deleted,status,merchant_id,address,amount,check_time,checker,no,purchase_time,purchaser,remark,state,supplier_id,supplier_name,type)\n" +
                "VALUES(now(),0,0,:merchant_id,:address,:amount,:check_time,:checker,:no,:purchase_time,:purchaser,:remark,:state,:supplier_id,:supplier_name,:type) ";
        QyMap params = QyMap.map("merchant_id",merchantId)
                .setv("address",order.getAddress())
                .setv("amount",order.getAmount())
                .setv("check_time",order.getCheckTime())
                .setv("checker",order.getChecker())
                .setv("no",order.getNo())
                .setv("purchase_time",order.getPurchaseTime())
                .setv("purchaser",order.getPurchaser())
                .setv("remark",order.getRemark())
                .setv("state",PurchaseState.WAIT.getKey())
                .setv("supplier_id",order.getSupplierId())
                .setv("supplier_name",order.getSupplierName())
                .setv("type", BranchPurchaseType.ZHIPEI.getKey());
        Long id = branchJdbcTemplate.insertForAutoIncrement(sql,params);
        BranchPurchaseOrderDetail detail = null;
        //添加订单明细
        if (CollectionUtils.isNotEmpty(detailList)){
            Map<String,?>[] maps = new Map[detailList.size()];
            for (int i = 0; i < detailList.size(); i++) {
                detail = detailList.get(i);
                params = QyMap.map("merchant_id",merchantId)
                        .setv("amount",detail.getPurchaseCount()*detail.getPurchasePrice())
                        .setv("count",detail.getPurchaseCount())
                        .setv("name",detail.getName())
                        .setv("no",detail.getNo())
                        .setv("price",detail.getPurchasePrice())
                        .setv("purchase_spec_name",detail.getPurchaseSpec())
                        .setv("purchase_unit_name",detail.getPurchaseUnit())
                        .setv("chain_remark",detail.getGroupRemark())
                        .setv("spec",detail.getMaterialSpec())
                        .setv("order_id",id)
                        .setv("spec_id",detail.getSpecId())
                        .setv("storage_unit_name",detail.getStockUnit())
                        .setv("remark",detail.getBranchRemark());
                maps[i] = params;
            }
            sql = "INSERT INTO purchase_order_details (create_at,is_deleted,status,merchant_id,amount,count,name,no,price,purchase_spec_name,purchase_unit_name,chain_remark,spec,order_id,spec_id,storage_unit_name,remark)\n" +
                    "VALUES(now(),0,0,:merchant_id,:amount,:count,:name,:no,:price,:purchase_spec_name,:purchase_unit_name,:chain_remark,:spec,:order_id,:spec_id,storage_unit_name,:remark) ";
            branchJdbcTemplate.batchUpdate(sql,maps);
        }

    }

    /**
     * 根据订单id 获取订单信息
     * @param id
     * @return
     */
    public Map<String,Object> getOrderData(Long id) {
        String sql = "SELECT * from purchase_orders where id = :id";
        QyMap params = QyMap.map("id",id);
        Map<String,Object> map = branchJdbcTemplate.queryForMap(sql,params);
        return map;
    }

    /**
     * 根据订单获取订单明细 按照id排序
     * @param id 顺
     * @return
     */
    public List<Map<String,Object>> getOrderDetailData(Long id) {
        String sql = "SELECT d.*,m.uuid,m.unit FROM purchase_order_details d \n" +
                "LEFT JOIN purchase_specs p ON p.id = d.spec_id\n" +
                "LEFT JOIN materials m ON m.id = p.material_id\n" +
                "WHERE order_id = :orderId ORDER BY id";
        QyMap map = QyMap.map("orderId",id);
        return branchJdbcTemplate.queryForList(sql,map);
    }

    /**
     * 修改订单状态为 未审核
     * @param no
     * @param branchId
     */
    public void updateOrderState(String no, Long branchId) {
        Long merchantId = branchService.getMerchantIdByBranchId(branchId);
        if (merchantId==null){
            throw new BusinessRunTimeException("商户不存在",10002);
        }
        log.info("merchantId :{}",merchantId);
        String sql = "select count(*) from purchase_orders where merchant_id = :merchantId and type=:type and no = :no";
        QyMap map = QyMap.NEW()
                .setv("merchantId",merchantId)
                .setv("type",BranchPurchaseType.ZICAI.getKey())
                .setv("no",no);
        long count = branchJdbcTemplate.queryForScalar(sql,map,Long.class);
        log.info("count : {}",count);
        if (count<=0){
            throw new BusinessRunTimeException("单店订单不存在",10001);
        }
        sql = "UPDATE purchase_orders set state = :state where merchant_id = :merchantId and type=:type and no = :no ";
        map = QyMap.map("state",PurchaseState.NOAUDIT.getKey())
                .setv("merchantId",merchantId)
                .setv("type",BranchPurchaseType.ZICAI.getKey())
                .setv("no",no);
        branchJdbcTemplate.update(sql,map);

    }

    /**
     * 单店订单类型
     */
    public enum PurchaseState {
        NOAUDIT("未审核"),
        AUDIT("已审核"),//待收货确认
        INSTORAGE("已入库"),
        WAIT("总部待发货");
        private final String text;
        private PurchaseState(String text) {
            this.text = text;
        }
        public String getKey() {
            return this.toString();
        }
        public String getText() {
            return text;
        }
    }
}